﻿(function () {

    'use strict';
    var blogType = 0;//微博数据来源类型

    angular.module('infinite-scroll').value('THROTTLE_MILLISECONDS', 1000)
    var fanfocusModule = angular.module("fanfocusModule", ['elif', 'blogService', 'commonApp', 'blogDirectiveModule']);
    fanfocusModule.controller("fanfcocusCtrl", function ($scope, $timeout, $rootScope, $http, microblogsService) {
        $scope.userId = $('.weibo_detail_wrap').attr('uid');//当前用户的id
        $scope.lookUserId = $('.weibo_wrap').attr('blog-user');//当前用户的id
        $scope.FansPager = {
            curPageTag: "Fans",
            startId: 0,
            pageIndex: 0, //页码
            itemList: [], //列表项
            TotalPages: 0 //总共多少页
        };

        $scope.FocusPager = {
            curPageTag: "Focus",
            startId: 0,
            pageIndex: 0, //页码
            itemList: [], //列表项
            TotalPages: 0 //总共多少页
        }

        $scope.Pager = {};

        var curPage = $scope.FansPager;

        $scope.isOpen = false;
        $scope.busyFan = true;//初始的时候禁用请求列表数据

        /**
         * 初始化获取列表的准备工作
         * @returns {boolean} 
         */
        $scope.initPending1 = function (tabFlag) {
            //不是当前页就不往下继续
            if (curPage.curPageTag != tabFlag)
                return false;

            var flag = ($(document).scrollTop() + $(window).height() == $(document).height());
            if ($scope.isOpen) {
                if (!flag) {
                    return false;
                }
            }

            if ($scope.busyFan) {
                return false;
            }
            if (curPage.pageIndex > curPage.TotalPages) {
                return false;
            }
            curPage.pageIndex += 1;
            $scope.busyFan = true;
            return true;
        }




        /**
     * 获取用户关注列表
     * @returns {} 
     */
        $scope.getUserFollowList = function () {
            var res = $scope.initPending1("Focus");
            if (!res) return;
            microblogsService.getUserFollowerList($scope.FocusPager.pageIndex, -1, $scope.lookUserId).then(function (response) {
                var dataList = response.data.list.Items;
                $scope.FocusPager.TotalPages = response.data.list.TotalPages;
                if (!dataList) {
                    $scope.busyFan = false;
                    return;
                }
                if (dataList.length > 0) {
                    $scope.isOpen = true;
                } else {
                    $scope.isOpen = false;
                    $scope.busyFan = false;
                }
                for (var i = 0; i < dataList.length; i++) {
                    $scope.FocusPager.itemList.push(dataList[i]);
                }
                $scope.busyFan = false;
            })
            //  $scope.Pager = $scope.FocusPager;
        }



        /**
            * 获取用户粉丝列表
            * @returns {} 
            */
        $scope.getUserBeFolloweredList = function () {
            var res = $scope.initPending1("Fans");
            if (!res) return;

            microblogsService.getUserBeFolloweredList($scope.FansPager.pageIndex, $scope.lookUserId).then(function (response) {
                var dataList = response.data.list.Items;
                $scope.FansPager.TotalPages = response.data.list.TotalPages;
                if (!dataList) {
                    $scope.busyFan = false;
                    return;
                }
                if (dataList.length > 0) {
                    $scope.isOpen = true;
                } else {
                    $scope.isOpen = false;
                    $scope.busyFan = false;
                }
                for (var i = 0; i < dataList.length; i++) {
                    $scope.FansPager.itemList.push(dataList[i]);
                }
                $scope.busyFan = false;
            })
        }




        //发布微博，评论，回复，各个小功能框点击的显示和隐藏
        $rootScope.showFollerUserDlg = function (e) {
            var inputId, divId;
            if (!$(e.target).attr('input-id')) {//当前子元素没有，去父元素找
                inputId = $(e.target).parent().attr('input-id');
                divId = $(e.target).parent().attr('div-id');
            } else {
                inputId = $(e.target).attr('input-id');
                divId = $(e.target).attr('div-id');
            }

            //滚动条
            //var nicesx = $(".nui-scroll").niceScroll({ touchbehavior: false, cursorcolor: "#a3a6af", cursoropacitymax: 0.6, cursorwidth: 8, horizrailenabled: false });

            if ($("#" + divId).is(":hidden")) { //显示的时候加载
                $rootScope.loadFollowers(e)
            }

            $("#" + divId).find('input').val('');
            $("#" + divId).toggle();
        }


        /**
         * 关注或取消关注
         * @param {$index}  
         * @returns {} 
         */
        $scope.AttentionUser = function ($index) {
            blogType = $('.fanAttention').attr('blog-type');
            var item = curPage.itemList[$index];
            var uid = item.MicroBlog ? item.MicroBlog.UserId : item.Id;
            var Func = function () {
                microblogsService.AttentionUser(uid, function (data) {
                    if (data != null && data) {
                        if (item.MicroBlog) {//普通的微博列表
                            for (var i = 0; i < curPage.itemList.length; i++) {
                                var cUid = curPage.itemList[i].MicroBlog.UserId;
                                if (cUid == uid) {
                                    curPage.itemList[i].IsAttention = !curPage.itemList[i].IsAttention;
                                }
                            }
                        } else {//其他列表的情况
                            if (item.IsAttention) { //取消关注
                                var text = $("#focussCount").text();
                                var match = text.match(/\d+/);
                                if (match) {
                                    var newNum = parseInt(match[0]) - 1;
                                    $("#focussCount").text(text.replace(/\d+/, newNum));
                                    $("#pageFocusCount").text(text.replace(/\d+/, newNum));
                                }
                                if (blogType == 4) { //当前是关注列表来的
                                    curPage.itemList.splice($index, 1);
                                } else if (blogType == 5) {//粉丝列表来的
                                    item.FollowerCount--;
                                    item.IsAttention = false;//取消关注
                                }
                            } else {//添加关注
                                var text = $("#focussCount").text();
                                var match = text.match(/\d+/);
                                if (match) {
                                    var newNum = parseInt(match[0]) + 1;
                                    $("#focussCount").text(text.replace(/\d+/, newNum));
                                    $("#pageFocusCount").text(text.replace(/\d+/, newNum));
                                }
                                if (blogType == 5) {//粉丝列表来的
                                    item.FollowerCount++;
                                    item.IsAttention = true;//设置为添加关注
                                }
                            }

                        }

                        //触发事件
                        getUserAssociate();
                    }
                });
            }

            if (item.IsAttention == true) {
                confirmBox('确定要取消关注吗?', function () {
                    Func();
                }, uid);
            } else {
                Func();
            }




        }

        /**
         * 关注或取消关注(从他的粉丝/关注列表)
         * @param {$index}  
         * @returns {} 
         */
        $scope.AttentionUserFromHisList = function ($index) {
            var item = curPage.itemList[$index];
            var uid = item.MicroBlog ? item.MicroBlog.UserId : item.Id;
            var Func = function () {
                microblogsService.AttentionUser(uid, function (data) {
                    if (data != null && data) {
                        if (item.IsAttentionByMySelf) { //取消关注
                            item.FollowerCount--;
                            item.IsAttentionByMySelf = false;//取消关注
                        } else {//添加关注
                            item.FollowerCount++;
                            item.IsAttentionByMySelf = true;//设置为添加关注
                        }
                        //触发事件
                        getUserAssociate();
                    }
                });
            }
            if (item.IsAttentionByMySelf == true) {
                confirmBox('确定要取消关注吗?', function () {
                    Func();
                }, uid);
            } else {
                Func();
            }
        }

        //顶部关注，该表blog列表的状态
        $scope.TopAttentionUser = function (userId, event) {
            var uid = userId;
            curPage = $scope.$parent.Pager;
            var Func = function () {
                microblogsService.AttentionUser(uid, function (data) {
                    if (data != null && data) {
                        if (true) {//普通的微博列表
                            for (var i = 0; i < curPage.itemList.length; i++) {
                                var cUid = curPage.itemList[i].MicroBlog.UserId;
                                if (cUid == uid) {
                                    curPage.itemList[i].IsAttention = !curPage.itemList[i].IsAttention;
                                }
                            }
                        }
                        else {//其他列表的情况
                        }
                        getUserAssociate();
                    }
                });
            }

            if (event.target.innerText == '已关注') {
                confirmBox('确定要取消关注吗?', function () {
                    Func();
                }, uid);
            } else {
                Func();
            }

        }


        /**
         * 用户关注
         * @returns {} 
         */
        $scope.LoadFocus = function () {
            curPage = $scope.FocusPager;
            $scope.FocusPager.itemList = [];
            $scope.FocusPager.pageIndex = 0;
            $scope.FocusPager.startId = 0;
            $scope.isOpen = false;
            $scope.busy = true;//禁用微博分页
            $scope.busyFan = false;
            $scope.disableBlogList();
            $scope.getUserFollowList();
        }


        /**
         * 用户粉丝
         * @param {Number} 24小时 or 48小时 
         * @returns {} 
         */
        $scope.LoadFans = function () {
            curPage = $scope.FansPager;
            $scope.FansPager.itemList = [];
            $scope.FansPager.pageIndex = 0;
            $scope.FansPager.startId = 0;
            $scope.isOpen = false;
            $scope.busy = true;//禁用微博分页
            $scope.busyFan = false;
            $scope.disableBlogList();
            $scope.getUserBeFolloweredList();
        }

        function getCurPage(tabFlag) {
            if (tabFlag == 'Focus')
                curPage = $scope.FocusPager;
            else
                curPage = $scope.FansPager;

            return curPage;
        }

        $scope.disableBlogList = function () {
            var appElement = document.querySelector('[ng-controller=MicroBlogCtrl]');
            if (appElement) {
                var $scopeBlog = angular.element(appElement).scope();
                $scopeBlog.busy = true;
            }
        }


        /**
        * 点击发送私信
        * @param {} $index 
        * @returns {} 
        */
        $scope.ShowPrivateLetterDlg = function ($index) {
            requiredLogin(function () {
                var userId, displayName;
                var item = curPage.itemList[$index] || curPage.itemList[$index];
                userId = item.MicroBlog ? item.MicroBlog.UserId : item.Id;
                displayName = item.MicroBlog ? item.MicroBlog.UserDisplayName : item.NickName;
                $scope.$emit('SHOW_LETTER_DIALOG', userId, displayName);
            })

        }

        /**
         * 普通的发送私信窗口
         * @param {} uid 
         * @param {} name 
         * @returns {} 
         */
        $scope.ShowPrivateLetter = function (uid, name) {
            requiredLogin(function () {
                $scope.$emit('SHOW_LETTER_DIALOG', uid, name);
            })
        }



    })
        .config([
            '$compileProvider', function ($compileProvider) {
                $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|javascript):/);
            }
        ]).filter('to_trusted', [
            '$sce', function ($sce) {
                return function (text) {
                    return $sce.trustAsHtml(text);
                };
            }
        ]);


}());


